<template>
  <div>
    <el-card>
      <el-table :data="permissions" style="width: 100%">
        <el-table-column prop="role" label="角色名称">
        </el-table-column>
        <el-table-column prop="permissions" label="权限列表">
          <template #default="{ row }">
            <el-tag v-for="(permission, index) in row.permissions" :key="index" :style="getTagStyle(permission)">
              {{ permission }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editRole(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="removeRole(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addNewRole">新增角色</el-button>
    </el-card>

    <!-- 新增角色对话框 -->
    <el-dialog v-model="dialogAddVisible" title="新增角色">
      <el-form :model="newRoleForm" :rules="rules" ref="newRoleRef">
        <el-form-item label="角色名称" prop="role">
          <el-input v-model="newRoleForm.role"></el-input>
        </el-form-item>
        <el-form-item label="权限列表" prop="permissions">
          <el-select v-model="newRoleForm.permissions" multiple placeholder="请选择权限">
            <el-option
                v-for="item in allPermissions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog v-model="dialogEditVisible" title="编辑角色">
      <el-form :model="editRoleForm" :rules="rules" ref="editRoleRef">
        <el-form-item label="角色名称" prop="role">
          <el-input v-model="editRoleForm.role"></el-input>
        </el-form-item>
        <el-form-item label="权限列表" prop="permissions">
          <el-select v-model="editRoleForm.permissions" multiple placeholder="请选择权限">
            <el-option
                v-for="item in allPermissions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const API_URL = 'http://60.205.189.235:90/api/v1/role'

export default {
  setup() {
    const permissions = ref([])

    const dialogAddVisible = ref(false)
    const newRoleForm = reactive({
      role: '',
      permissions: []
    })
    const allPermissions = [
      { value: '源数据管理', label: '源数据管理' },
      { value: '角色管理', label: '角色管理' },
      { value: '数据分析', label: '数据分析' },
      { value: '联盟协作组管理', label: '联盟协作组管理' },
      { value: '周报管理', label: '周报管理' },
      { value: '邮件管理', label: '邮件管理' },
      { value: '日志管理', label: '日志管理' }
    ]
    const rules = reactive({
      role: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      permissions: [{ required: true, message: '请选择权限', trigger: 'change' }]
    })

    const dialogEditVisible = ref(false)
    const editRoleForm = reactive({
      role: '',
      permissions: []
    })

    const deleteRoleForm = reactive({
      role: ''
    })

    // 获取权限列表
    const fetchPermissions = async () => {
      try {
        const response = await axios.post(API_URL+"/selectAll")
        permissions.value = response.data
        //permissions.value.push({ role: 'admin', permissions: ['读取', '写入', '修改', '删除'] })
      } catch (error) {
        console.error('Error fetching permissions:', error)
        ElMessage.error('获取权限列表失败')
      }
    }

    // 新增角色
    const addNewRole = () => {
      dialogAddVisible.value = true
    }

    const submitNewRole = async () => {
      if (newRoleForm.role && newRoleForm.permissions.length > 0) {
        try {
          await axios.post(API_URL+"/add", newRoleForm)
          fetchPermissions()
          dialogAddVisible.value = false
          ElMessage.success('角色添加成功')
        } catch (error) {
          console.error('Error adding new role:', error)
          ElMessage.error('角色添加失败')
        }
      }
    }

    // 编辑角色
    const editRole = (role) => {
      editRoleForm.role = role.role
      editRoleForm.permissions = [...role.permissions]
      dialogEditVisible.value = true
    }

    const submitEditRole = async () => {
      if (editRoleForm.role && editRoleForm.permissions.length > 0) {
        try {
          await axios.post(API_URL+"/edit", editRoleForm) //编辑跟新增逻辑一样
          fetchPermissions()
          dialogEditVisible.value = false
          ElMessage.success('角色编辑成功')
        } catch (error) {
          console.error('Error editing role:', error)
          ElMessage.error('角色编辑失败')
        }
      }
    }

    // 删除角色
    const removeRole = async (role) => {
      try {
        deleteRoleForm.role = role.role
        await axios.post(API_URL+"/delete",deleteRoleForm)
        fetchPermissions()
        ElMessage.success('角色删除成功')
      } catch (error) {
        console.error('Error deleting role:', error)
        ElMessage.error('角色删除失败')
      }
    }

    const getTagStyle = (permission) => {
      switch (permission) {
        case '源数据管理':
          return { background: '#409EFF' }
        case '角色管理':
          return { background: '#E6A23C' }
        case '数据分析':
          return { background: '#67C23A' }
        case '联盟协作组管理':
          return { background: '#F56C6C' }
        case '周报管理':
          return { background: '#67C23A' }
        case '邮件管理':
          return { background: '#E6A23C' }
        case '日志管理':
          return { background: '#409EFF' }
        default:
          return {}
      }
    }

    // 初始化加载权限列表
    onMounted(() => {
      fetchPermissions()
    })

    return {
      permissions,
      dialogAddVisible,
      newRoleForm,
      allPermissions,
      rules,
      addNewRole,
      submitNewRole,
      dialogEditVisible,
      editRoleForm,
      editRole,
      submitEditRole,
      removeRole,
      getTagStyle
    }
  }
}
</script>

<style scoped>
/* 样式 */
</style>
